<template>
  <n-card :bordered="false" class="proCard">
    <BasicForm @register="register" @reset="handleReset" @submit="handleSubmit">
      <template #chanListSelect="{ model, field }">
        <n-select v-model:value="model[field]" :options="chanOptions" multiple />
      </template>
    </BasicForm>

    <BasicTable
      ref="actionRef"
      :actionColumn="actionColumn"
      :columns="columns"
      :loading="dataLoading"
      :request="loadDataTable"
      :row-key="(row) => row.id"
      :scroll-x="1090"
      @update:checked-row-keys="onCheckedRow"
    >
      <template #tableTitle>
        <n-button type="primary" @click="handlerAddAnchor">
          <template #icon>
            <n-icon>
              <PlusOutlined />
            </n-icon>
          </template>
          添加主播
        </n-button>
      </template>
      <template #toolbar>
        <n-space>
          <n-button v-if="isDelete" type="error" @click="batchDelete">批量删除</n-button>
          <n-button type="primary" @click="reloadTable">刷新数据</n-button>
        </n-space>
      </template>
    </BasicTable>
  </n-card>
  <basicModal
    ref="modalRef"
    class="basicModal"
    style="width: 30%"
    @register="modalRegister"
    @on-ok="okModal"
  >
    <template #default>
      <BasicForm class="basicForm" @register="addRegister">
        <template #chanSelect="{ model, field }">
          <n-select v-model:value="model[field]" :options="chanOptions" clearable />
        </template>

        <template #makeDate="{ model, field }">
          <n-date-picker
            v-model:value="model[field]"
            :is-date-disabled="dateDisableVaildate"
            type="datetime"
          />
        </template>
      </BasicForm>
    </template>
  </basicModal>
</template>

<script lang="ts" setup>
  import { h, onMounted, reactive, ref, unref } from 'vue';
  import { useDialog, useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { addCloumns, columns } from './columns';
  import { DeleteOutlined, EditOutlined, PlusOutlined } from '@vicons/antd';
  import { useModal } from '@/components/Modal';
  import { getChanList } from '@/api/game/chan';
  import {
    deleteAnchor,
    getAnchorFilter,
    registerAnchor,
    updateAnchor,
  } from '@/api/liveBroadcast/anchorManage';
  import { useUserStore } from '@/store/modules/user';

  const chanOptions = ref([]);
  const dataLoading = ref(false);
  const schemas: FormSchema[] = [
    {
      field: 'chanIdList',
      label: '渠道昵称',
      slot: 'chanListSelect',
    },
  ];

  const formRef: any = ref(null);
  const message = useMessage();
  const userStore = useUserStore();
  const isDelete = userStore.getRoleType == 'admin' || userStore.getRoleType == 'super';
  const dialog = useDialog();
  const actionRef = ref();
  const checkedRowKes = ref([]);
  const tableDataSource = ref([]);
  const showModal = ref(false);
  const isEdit = ref(false);
  const formParams = reactive({
    chanIdList: '',
  });
  const updateEntity = ref({});

  const editParams = reactive({
    adveristCost: 0,
    anchorId: 0,
    anchorName: '',
    chanId: '',
    createTime: '',
    startTime: '',
    updateTime: '',
  });

  const actionColumn = reactive({
    width: isDelete ? 200 : 150,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            onClick: handleEditAnchor.bind(null, record),
            type: 'info',
            icon: EditOutlined,
            ifShow: () => {
              return true;
            },
          },
          {
            label: '删除',
            onClick: handleDeleteAnchor.bind(null, record),
            type: 'error',
            icon: DeleteOutlined,
            ifShow: () => {
              return isDelete;
            },
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 120,
    schemas,
  });

  //打开添加主播面板
  async function handlerAddAnchor() {
    isEdit.value = false;
    await openModal();
    setProps({ title: '添加' });
    updateEntity.value = {};
  }

  const [modalRegister, { openModal, closeModal, setSubLoading, setProps }] = useModal({
    title: '编辑',
  });

  const [addRegister, { submit: addSubmit, setFieldsValue: addSetFieldsValue }] = useForm({
    gridProps: { cols: 1 },
    collapsedRows: 3,
    labelWidth: 120,
    layout: 'horizontal',
    submitButtonText: '提交保存',
    showActionButtonGroup: false,
    schemas: addCloumns,
  });

  function dateDisableVaildate(
    current: number,
    phase: 'start' | 'end',
    value: [number, number] | null
  ) {
    return current < new Date().getTime();
  }

  async function okModal() {
    let formValue;
    try {
      formValue = await addSubmit();
    } catch (e) {
      message.error('请填写完整信息');
      return;
    } finally {
      setSubLoading(false);
    }
    try {
      let value: any = Object.assign({}, editParams, formValue || {});
      let adveristCost = parseFloat(value.adveristCost).toFixed(2);
      value.adveristCost = Number(adveristCost);
      if (isEdit.value) {
        value = Object.assign({}, unref(updateEntity), value, {
          anchorId: unref(updateEntity).anchorId,
        });
        await updateAnchor(value);
        message.success('编辑成功');
      } else {
        await registerAnchor(value);
        message.success('添加成功');
      }
      closeModal();
    } finally {
      setSubLoading(false);
    }

    await reloadTable();
  }

  const loadDataTable = async (res) => {
    const param = { ...formParams, ...res }; //分页的关键
    console.log(param);
    let data = await getAnchorFilter(param);
    tableDataSource.value = data ? data : [];
    return data;
  };

  async function reloadTable() {
    // try {
    //   dataLoading.value = true;
    //   await loadDataTable();
    //   actionRef.value.reload();
    // } finally {
    //   dataLoading.value = false;
    // }
    actionRef.value.reload();
  }

  function onCheckedRow(rowKeys: any[]) {
    checkedRowKes.value = rowKeys;
  }

  async function handleEditAnchor(record: Recordable) {
    isEdit.value = true;
    await openModal();
    setProps({ title: '编辑' });
    updateEntity.value = record;
    Object.assign(record, {
      liveTime: new Date(unref(record).liveTime).getTime(),
      adveristCost: unref(record).adveristCost + '',
    });
    await addSetFieldsValue(record);
  }

  async function handleDeleteAnchor(record: Recordable) {
    dialog.info({
      title: '提示',
      content: `您想删除${record.anchorName}吗`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        let anchorArrs = [];
        anchorArrs.push(
          Object.assign({}, unref(record), { anchorId: parseInt(unref(record).anchorId) })
        );
        await deleteAnchor({
          anchorArrs,
        });
        message.success('删除成功');
        await reloadTable();
      },
      onNegativeClick: () => {},
    });
  }

  //批量删除
  function batchDelete() {
    const anchorIds = unref(checkedRowKes);
    if (anchorIds.length === 0) {
      message.warning('至少选择一条数据');
      return;
    }
    dialog.info({
      title: '提示',
      content: `您想删除选中主播吗`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        let anchorArrs = [];
        anchorIds.forEach((value) => {
          anchorArrs.push(Object.assign({}, editParams, { anchorId: value }));
        });
        await deleteAnchor({ anchorArrs });
        message.success('删除成功');
        reloadTable();
      },
      onNegativeClick: () => {},
    });
  }

  function handleSubmit(values: Recordable) {
    console.log(values);
    if (unref(values) && unref(values).chanIdList.length > 0) {
      Object.assign(unref(formParams), { chanIdList: unref(values).chanIdList.join(',') });
    }
    reloadTable();
  }

  function handleReset(values: Recordable) {
    reloadTable();
  }

  onMounted(async () => {
    await loadDataTable();
    const chanList = await getChanList({
      page: 0,
      pageSize: 10,
      chanName: '',
    });
    console.log(chanList);
    chanOptions.value = chanList.list.map((chan) => {
      return {
        label: chan.chanName,
        value: chan.chanId,
      };
    });
  });
</script>

<style lang="less" scoped></style>
